import { app, BrowserWindow, Notification, ipcMain } from 'electron'
import '../renderer/store'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
      nodeIntegration: true //在网页中集成Node
    }
  })

  mainWindow.loadURL(winURL)

  mainWindow.setMenu(null);

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  handleIPC()
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

function handleIPC() {
  ipcMain.handle("work-notification", async () => {
    let res = await new Promise((resolve, reject) => {
      let notification = new Notification({
        title: "任务结束",
        body: "是否重置任务？",
        actions: [{ text: "重置", type: "button" }],
        closeButtonText: "等待"
      })
      notification.show();
      let msg = new Notification({
        title: "提示",
        body: "新任务即将开始",
      })
      notification.on("click", () => {
        msg.show()
        resolve("reset")
      })
      notification.on("action", () => {
        msg.show()
        resolve("reset")
      })
      notification.on("close", () => {
        resolve("wait")
      })
    })
    return res;
  })
}

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
